package com.copa.provider.music.netease;

import com.alibaba.fastjson.JSONObject;

import com.copa.api.MusicApi;
import com.copa.entity.Music;
import com.copa.utils.AES;
import com.copa.utils.SongUtils;
import org.apache.commons.codec.binary.Hex;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

/**
 * Created by haohua on 2018/2/10.
 */
@SuppressWarnings("SpellCheckingInspection")
public class NeteaseMusicApi implements MusicApi {
    private static final String SECRET = "7246674226682325323F5E6544673A51";


    @Override
    public List<Music> searchMusicSync(String keyword, int page, boolean needLink) throws IOException {
        List<Music> result = new NeteaseSearchMusicRequest(keyword, page).requestSync();
        SongUtils.fillSongLinks(result, mGetSongLinksRequestFunction);
        if (needLink) {
            // 需要下载歌曲，直接跳过下载页面
            result.forEach(music -> music.setJumpUrl(music.getMusicUrl()));
        }
        return result;
    }

    static String encrypt(JSONObject json) {
        return encrypt(json.toString());
    }

    static String encrypt(String raw) {
        byte[] encrypted;
        try {
            encrypted = AES.encrypt(raw, Hex.decodeHex(SECRET.toCharArray()));
            return new String(Hex.encodeHex(encrypted)).toUpperCase();
        } catch (Exception e) {
            e.printStackTrace();

        }
        return null;
    }

    public static String[] getSongIdsFromSongList(List<Music> musicList) {
        ArrayList<String> musicIds = new ArrayList<>();
        for (Music music : musicList) {
            musicIds.add(music.getMusicUrl().substring(music.getMusicUrl().indexOf("id=") + 3));
        }
        return musicIds.toArray(new String[]{});
    }

    private Function<String[], List<Music>> mGetSongLinksRequestFunction = musicIds -> {
        try {
            return new NeteaseGetMusicLinksRequest(musicIds).requestSync();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    };
}
